package com.stock.stockana.ui.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.TextView;

import com.andexert.library.RippleView;
import com.stock.publiclib.utils.StringUtil;
import com.stock.stockana.beans.StockInfoBean;
import com.stock.stockana.requests.GetAllStocks;
import com.stock.stockana.ui.activities.MainActivity;
import com.stock.stockana.R;
import com.stock.stockana.StockCenter;
import com.stock.stockana.beans.StockInfo;
import com.stock.stockana.requests.GetRecStocks;
import com.stock.stockana.ui.custom.QNumberPicker;
import com.stock.stockana.ui.listener.OnStockItemClickedListener;

import java.util.List;

/**
 * ---------------------------------------------------
 * Description: 推荐股票页面,股票列表适配器
 * Author: ljgsonx
 * Belong to: com.stock.stockana.ui.adapter
 * Time: 2016/1/26 16:29
 * ---------------------------------------------------
 */
public class RecomStockAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context mContext;
    private LayoutInflater mLayoutInflater;

    private final static int VIEWTYPE_HEADER = 0;
    private final static int VIEWTYPE_CONTENT = 1;

    private Button selectorBtn;
    private LinearLayout noItemTipLL;
    private QNumberPicker np1;
    private QNumberPicker np2;
    private QNumberPicker np3;
    private String[] npValues = new String[]{"跌幅","涨幅","混合"};

    private View selectorView;
    private int selectorViewHeight;
    private boolean finishedGetData = false;

    private List<StockInfo> recomStocks;

    private OnStockItemClickedListener mOnStockItemClickedListener;

    public void setmOnStockItemClickedListener(OnStockItemClickedListener onStockItemClickedListener){
        this.mOnStockItemClickedListener = onStockItemClickedListener;
    }

    public RecomStockAdapter(Context context) {
        this.mContext = context;
        this.mLayoutInflater = LayoutInflater.from(mContext);
        recomStocks = GetRecStocks.stocks;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder holder = null;
        switch (viewType) {
            case VIEWTYPE_HEADER:
                holder = initHeader(parent);
                break;
            case VIEWTYPE_CONTENT:
                holder = new StocksHolder(mLayoutInflater.inflate(R.layout.recom_stock_item, parent, false));
                break;
            default:
                break;
        }
        return holder;
    }

    private RecyclerView.ViewHolder initHeader(final ViewGroup parent) {
        View titleView = mLayoutInflater.inflate(R.layout.recom_stock_header, parent, false);
        np1 = (QNumberPicker) titleView.findViewById(R.id.np1);
        np2 = (QNumberPicker) titleView.findViewById(R.id.np2);
        np3 = (QNumberPicker) titleView.findViewById(R.id.np3);
        selectorBtn = (Button) titleView.findViewById(R.id.selectBtn);
        noItemTipLL = (LinearLayout) titleView.findViewById(R.id.noItemTipLL);
        np1.setMaxValue(30);
        np1.setMinValue(1);
        np1.setValue(15);
        np2.setDisplayedValues(npValues);
        np2.setMaxValue(npValues.length - 1);
        np2.setMinValue(0);
        np2.setValue(0);
        np3.setMaxValue(30);
        np3.setMinValue(1);
        np3.setValue(6);
        np1.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        np2.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        np3.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        selectorBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectorView = ((ViewGroup)(parent.getChildAt(0))).getChildAt(0);
                if(selectorView.getHeight() != 0){
                    selectorViewHeight = selectorView.getHeight();
                    selectorToggle(-selectorViewHeight);
                }else{
                    if(finishedGetData){
                        selectorToggle(selectorViewHeight);
                    }
                }
            }

            void selectorToggle(final float toggleHeight){
                TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, 0, toggleHeight);
                translateAnimation.setDuration(600);
                translateAnimation.setFillAfter(true);
                translateAnimation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {}

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        parent.clearAnimation();
                        if(toggleHeight < 0){
                            selectorView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
//                            selectorBtn.setText(mContext.getResources().getString(R.string.title_recom_selectorBtn));
                            String trendText;
                            if (np2.getValue() == 2) {
                                trendText= "跌幅/涨幅";
                            }else{
                                trendText= npValues[np2.getValue()];
                            }
                            String btnText = "最近" + np1.getValue() + "个交易日," + trendText + "大于" + np3.getValue() + "%";
                            selectorBtn.setText(btnText);
                            int recentDays = np1.getValue();
                            int chooseMode = np2.getValue();
                            int percentLimit = np3.getValue();
                            finishedGetData = false;
                            recomStocks.clear();
                            notifyDataSetChanged();
                            GetRecStocks getRecStocks = GetRecStocks.build()
                                    .setChooseMode(chooseMode+"")
                                    .setPercentLimit(percentLimit+"")
                                    .setRecentDays(recentDays + "");
                            StockCenter.doReq(getRecStocks);
                            ((MainActivity)mContext).startPopLoading(parent,"正在搜索..");
                        }else{
                            selectorBtn.setText(mContext.getResources().getString(R.string.title_recom_selectorBtn_confirm));
                            selectorView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                        }
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {}
                });
                parent.startAnimation(translateAnimation);
            }
        });
        return new HeaderHolder(titleView);
    }

    public void allowOpenStockSelector(){
        this.finishedGetData = true;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return VIEWTYPE_HEADER;
        }else{
            return VIEWTYPE_CONTENT;
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        if (position != 0) {
            configViews((StocksHolder)holder,position-1);
            if(null != mOnStockItemClickedListener){
                ((RippleView)holder.itemView.findViewById(R.id.stockItemRv)).setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
                    @Override
                    public void onComplete(RippleView rippleView) {
                        String stockNum = recomStocks.get(position - 1).getStNum();
                        for (StockInfoBean sb : GetAllStocks.stocks) {
                            if (!StringUtil.isBlank(stockNum)) {
                                if (stockNum.equals(sb.getStNum())) {
                                    mOnStockItemClickedListener.onStockItemCliked(sb);
                                    break;
                                }
                            }
                        }
                    }
                });
            }
        }else {
            //重新筛选时,清空数据后,隐藏提示
            if (noItemTipLL.getVisibility() == View.VISIBLE) {
                noItemTipLL.setVisibility(View.GONE);
            }
            //筛选网络结果返回后,根据条件隐藏显示提示
            if (finishedGetData) {
                if (recomStocks.size() > 0) {
                    noItemTipLL.setVisibility(View.GONE);
                } else {
                    noItemTipLL.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    private void configViews(StocksHolder holder,int position) {
        holder.stockNameTv.setText(recomStocks.get(position).getStName());
        holder.stockNumTv.setText(recomStocks.get(position).getStNum());
        holder.downNumTv.setText(recomStocks.get(position).getDecTime()+"");
        holder.upNumTv.setText(recomStocks.get(position).getRiseTime()+"");
        holder.downTrendTv.setText(recomStocks.get(position).getDecRate() + "%");
        holder.upTrendTv.setText("+"+recomStocks.get(position).getRisRate() + "%");
    }

    @Override
    public int getItemCount() {
        return 1 + recomStocks.size();
    }

    class HeaderHolder extends RecyclerView.ViewHolder {

        public HeaderHolder(View itemView) {
            super(itemView);
        }
    }

    class StocksHolder extends RecyclerView.ViewHolder{
        public TextView stockNumTv;
        public TextView stockNameTv;
        public TextView upNumTv;
        public TextView downNumTv;
        public TextView upTrendTv;
        public TextView downTrendTv;

        public StocksHolder(View view) {
            super(view);
            this.stockNumTv = (TextView) view.findViewById(R.id.stockNumTv);
            this.stockNameTv = (TextView) view.findViewById(R.id.stockNameTv);
            this.upNumTv = (TextView) view.findViewById(R.id.upNumTv);
            this.downNumTv = (TextView) view.findViewById(R.id.downNumTv);
            this.upTrendTv = (TextView) view.findViewById(R.id.upTrendTv);
            this.downTrendTv = (TextView) view.findViewById(R.id.downTrendTv);
        }
    }

}
